package com.swm.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.swm.mapper.StockMapper;
import com.swm.pojo.Stock;
import org.apache.ibatis.session.SqlSession;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.swm.util.ConditionUtilDC.getMoneyUp;

/**
 * @author 师文明
 * @data 2024/12/23 下午3:11
 **/
public class getStockDayData33 {

    public static int allup;
    public static double allupnum;
    public static int numu;
    public static int numd;
    static SqlSession sqlSession = SqlSessionUtil.openSession();
    static StockMapper mapper = sqlSession.getMapper(StockMapper.class);

    public static List<Stock> getStcokList() {
        List<Stock> stocks = mapper.selectAllStock();
        JSONObject jsonObject = new JSONObject();

        for (Stock stock : stocks) {
            String code = stock.getCode();
            int type = stock.getType();
            jsonObject.put(code, type);

        }
        return stocks;
    }

    public static void main(String[] args) throws Exception {

        ExecutorService executorService = Executors.newFixedThreadPool(50);
        //获取所有股票列表
        List<Stock> stcokList = getStcokList();
        for (Stock stock : stcokList) {
            executorService.execute(() -> {
                try {
                    getData(stock.getCode(), stock.getType());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }

        Thread.sleep(40000);
        double v = 0;
        if (allup != 0) {
            v = allupnum / allup;
        }
        DecimalFormat df = new DecimalFormat("#0.00");
        System.out.println(("上涨次数" + numu + "  下跌次数" + numd));
        System.out.println(("平均涨幅：" + v + "上涨概率 " + df.format((double) numu / allup)));
        // 关闭线程池，以优雅的方式

        executorService.shutdown();

        // 关闭线程池，以优雅的方式
        // 关闭线程池，以优雅的方式
    }

    public static void getData(String code, int type) throws Exception {

        String data = getWebData(code, type);
        if (data == null) {
            return;
        }

        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get("data") != null) {
            JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("data").toString());
            String name = jsonObject1.get("name").toString();
            JSONArray klines = JSONArray.parse(jsonObject1.get("klines").toString());

            if (klines.size() > 161) {

                for (int i = 1; i < 100; i++) {
                    double price0 = Double.parseDouble(klines.get(klines.size() - i - 1).toString().split(",")[2]);
                    //日线
                    double totalsix1 = 0.0;
                    double totalth1 = 0.0;
                    double totaltw1 = 0.0;
                    double totalte1 = 0.0;
                    double totalf1 = 0.0;
                    for (int j = 1; j < 61; j++) {
                        double price = Double.parseDouble(klines.get(klines.size() - (i + j)).toString().split(",")[2]);
                        if (j < 6) {
                            totalf1 += price;
                        }
                        if (j < 11) {
                            totalte1 += price;
                        }
                        if (j < 21) {
                            totaltw1 += price;

                        }
                        if (j < 31) {
                            totalth1 += price;

                        }
                        totalsix1 += price;

                    }
                    double six1 = totalsix1 / 60;
                    double th1 = totalth1 / 30;
                    double tw1 = totaltw1 / 20;
                    double te1 = totalte1 / 10;
                    double f1 = totalf1 / 5;

                    //几天内有放量
                    boolean moneyUp = getMoneyUp(klines, 5, i);
                    //5天前 5天范围内振幅小，成交量稳定
                    boolean amplitude = getAmplitude(klines);

                    double k = Double.parseDouble(klines.get(klines.size() - i - 1).toString().split(",")[1]);
                    double vs0 = Double.parseDouble(klines.get(klines.size() - i - 1).toString().split(",")[2]);
                    double v = Double.parseDouble(klines.get(klines.size() - i - 1).toString().split(",")[8]);

                    //次日涨幅
                    double v1 = Double.parseDouble(klines.get(klines.size() - i).toString().split(",")[8]);
                    boolean b = k < f1 && k < te1 && k < tw1 && k < th1;
                    boolean b1 = vs0 > f1 && vs0 > te1 && vs0 > tw1 && vs0 > th1;
                    if (b && b1 && v < 9.8 && v > -9.8/*&&moneyUp&&amplitude&&price0>f1&&f1>te1*//*&&te1<six1&&p1<40*//*&&v1>numbers.get(109)&&f1>te1&&p1<prices.get(50)*/) {
                        //当天收盘
                        allupnum += v1;
                        allup++;
                        if (v1 > 0 || v1 == 0) {
                            numu++;
                        } else {
                            numd++;
                        }
                        System.out.println(name + " : " + klines.get(klines.size() - i - 1).toString().split(",")[0] + "  次日涨幅" + v1);
                    }
                }


            }
        }
    }


    public static String getWebData(String code, int type) {
        String data = null;
        try {
            // 连接到新浪财经接口
            String url = "https://push2his.eastmoney.com/api/qt/stock/kline/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f116,f117&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&beg=0&end=20500101&rtntype=6&secid=" + type + "." + code + "&klt=101&fqt=1";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Cookie", "qgqp_b_id=488de58836c5f30c189b9ad4c700b9f5; st_si=04137509447995; websitepoptg_api_time=1734056942833; st_asi=delete; HAList=ty-1-603999-%u8BFB%u8005%u4F20%u5A92%2Cty-0-002888-%u60E0%u5A01%u79D1%u6280%2Cty-0-002269-%u7F8E%u90A6%u670D%u9970%2Cty-0-000813-%u5FB7%u5C55%u5065%u5EB7%2Cty-0-002045-%u56FD%u5149%u7535%u5668%2Cty-0-300059-%u4E1C%u65B9%u8D22%u5BCC%2Cty-1-688605-N%u5148%u950B%2Cty-1-000001-%u4E0A%u8BC1%u6307%u6570; st_pvi=62081555482493; st_sp=2024-12-11%2010%3A26%3A42; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=60; st_psi=20241213164756225-113200301201-5528754653");
            // 设置连接超时时间为 10 秒
            con.setConnectTimeout(10000);
            // 设置读取超时时间为 10 秒
            con.setReadTimeout(10000);
            // 从数据源获取实时股票数据
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            con.disconnect();
            data = response.toString();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            //e.printStackTrace();
        }

        return data;
    }


    //获取最近成交额稳定价格稳定是否存在
    public static boolean getAmplitude(JSONArray klines) {

        //最近几天内
        int days = 5;
        //往前推的天数
        int bedays = 21;

        //从哪天开始 1就是今天
        int startDay = 1;

        double max = 0;
        double min = 1000000000;
        double average = 0;
        double total = 0;

        double maxprice = 0;
        double minprice = 10000;

        //
        boolean priceflag = false;
        //十天振幅
        for (int num = startDay; num < days; num++) {
            double price0 = Double.parseDouble(klines.get(klines.size() - num).toString().split(",")[2]);
            for (int i = num; i < (num + bedays); i++) {
                String[] split = klines.get(klines.size() - i).toString().split(",");
                double price = Double.parseDouble(split[2]);
                maxprice = Math.max(price, maxprice);
                minprice = Math.min(price, minprice);
                minprice = price < minprice ? price : min;
            }
            double priceDiff = (maxprice - minprice) / price0;
            if (priceDiff < 0.1) {
                priceflag = true;
            }
        }

        boolean moneyflag = false;
        for (int num = startDay; num < days; num++) {
            for (int i = num; i < (num + bedays); i++) {
                String[] split = klines.get(klines.size() - i).toString().split(",");
                double money = Double.parseDouble(split[5]);
                max = Math.max(money, max);
                min = Math.min(money, min);
                total += money;
            }
            average = total / bedays;
            //十天内成交量振幅
            double v3 = (max - min) / average;
            if (v3 < 1) {
                moneyflag = true;
            }
        }
        return priceflag && moneyflag;
    }
}

